package parse

import (
	"os"
	"github.com/PuerkitoBio/goquery"
	"bufio"
	"log"
	"strings"
)

type Table struct {
	Header []string
	Body   [][]string
}

func queryHtml(file *os.File) *goquery.Document {
	reader := bufio.NewReader(file)
	doc, err := goquery.NewDocumentFromReader(reader)
	doc.Contents()
	if err != nil {
		log.Fatal(err)
	}
	return doc
}

func (table *Table) GetBody(file *os.File) {
	doc := queryHtml(file)
	doc.Find("tbody tr").Each(func(i int, selection *goquery.Selection) {
		var info []string
		td := selection.Find("td")
		for i := 0; i < td.Length(); i++ {
			text := td.Eq(i).Text()
			info = append(info, text)
		}
		table.Body = append(table.Body, info)
	})
}

func (table *Table) GetHeader(file *os.File) {
	doc := queryHtml(file)
	doc.Find("thead tr").Each(func(i int, selection *goquery.Selection) {
		th := selection.Find("th")
		for i := 0; i < th.Length(); i++ {
			text := strings.TrimSpace(th.Eq(i).Text())

			table.Header = append(table.Header, text)
		}
	})
}
